import React, {Component} from 'react';
import {
    Modal,
    FlatList,
    StyleSheet,
    View,
    TouchableOpacity,
    TextInput,
    Text,
} from 'react-native';
import {Button} from '@ant-design/react-native';
import GlobalStyles from '../../common/styles/GlobalStyles';
import AntDesign from 'react-native-vector-icons/AntDesign';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import {StylesConstant} from '../../common/Constant';
import HttpUtils from '../../expand/dao/HttpUtils';
import {BASE_URL} from '../../common/BASE_URL';
import ToastUtil from '../../utils/ToastUtil';
import TreeSelect from 'react-native-tree-select';


export default class ChooseDeptDialog extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchText: '',
            dataList: [],
            visible: false,
            loading: true,
            id: '',
            label: ''
        };
    }

    show() {
        this.canClose = false;
        this.loadDataList()
        this.setState({
            id: '',
            label: '',
            visible: true,
        });
    }

    dismiss() {
        this.setState({
            visible: false,
        });
    }

    loadDataList(){
        this.state.loading = true
        HttpUtils.request({
            url: BASE_URL.apiBaseUrl + '/api/dept/deptTree',
        }).then((res) => {
            // console.log(res)
            if(res){
                const list = res.content
                this.setState({
                    loading: false,
                    dataList: list
                })
            }
        }).catch(() => {
            ToastUtil.info('网络异常,请稍后再试');
            this.setState({
                loading: false
            })
        });
    }



    clickItem(item) {
        this.props.onChoose && this.props.onChoose(item);
        this.dismiss()
    }

    _renderItem(data) {
        const {item} = data
        return (
            <TouchableOpacity
                onPress={() => this.clickItem(item)}
                style={{ backgroundColor: 'white',
                    padding: 10,
                    borderBottomWidth: 1,
                    borderColor: '#efefef'
                }}
            >
                <View style={{alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between',marginBottom: 8}}>
                    <View style={{flexDirection: 'row', flex: 1}}>
                        <FontAwesome
                            name={'user'}
                            size={16}
                            style={{color: StylesConstant.themeIconColor, marginRight: 10}}
                        />
                        <Text style={{flex: 2}}>{item.name && item.name.length > 6 ? item.name.substring(0, 5) + '.' : item.name}</Text>
                        <Text style={{flex: 1}}>{item.gender==1?'男':'女'}</Text>
                    </View>
                    <View style={{flex: 1}}><Text>{item.contactPhone }</Text></View>
                </View>
                <View style={{alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between',}}>
                    <View style={{flexDirection: 'row', flex: 1}}>
                        <FontAwesome
                            name={'building'}
                            size={16}
                            style={{color: StylesConstant.themeIconColor, marginRight: 10}}
                        />
                        <View style={{flex: 1}}><Text>{item.unitName || '- -'}</Text></View>
                    </View>
                </View>
            </TouchableOpacity>
        );
    }

    _filterResult(result) {
        const text = this.state.searchText;
        if (!result || result.length === 0 || !text) {
            return result;
        } else {
            const data = result.filter(item => {
                return (item.name && item.name.indexOf(text) !== -1) ||
                    (item.contactPhone && item.contactPhone.indexOf(text) !== -1) ||
                    (item.contactAddress && item.contactAddress.indexOf(text) !== -1);
            });
            return data;
        }
    }
    _onClick(data){
        // console.log(data.item);
        const {id,label} = data.item
        // console.log(id,label)
        this.state.id = id
        this.state.label = label
    }
    _onClickLeaf(item){
        // console.log(item);
        // const {id,label} = item
    }
    _chooseData(){
        const {id, label} = this.state
        console.log(id, label)
        if(!id || !label){
            ToastUtil.info('请先选择部门')
            return
        }
        this.props.onChoose({id,label})
        this.dismiss()
    }


    renderContentView() {
        const {dataList,loading} = this.state;
        let result = dataList
        const filterData = this._filterResult(result) || [];
        // console.log(result);
        return (
            <Modal
                animationType={'slide'}
                transparent={true}
                visible={this.state.visible}
                onRequestClose={() => {
                    if (!this.canClose) {
                        this.dismiss();
                        this.setState({
                            searchText: '',
                        });
                    }
                }}
            >
                <View style={[GlobalStyles.modalContainer,{borderWidth:1,borderColor: '#efefef',}]}>
                    <View style={GlobalStyles.searchInputContainer}>
                        <TextInput
                            style={GlobalStyles.searchIpt}
                            ref="input"
                            multiline={false}
                            placeholder={'关键字检索'}
                            onChangeText={(text) => {
                                this.setState({
                                    searchText: text,
                                });
                            }}
                        />
                        {!this.canClose ?
                            <TouchableOpacity onPress={() => {
                                this.dismiss();
                                this.setState({
                                    searchText: '',
                                });
                            }}>
                                <AntDesign
                                    name={'closecircle'}
                                    size={18}
                                    style={{paddingLeft: 5, paddingRight: 5, marginLeft: 5}}
                                    color={StylesConstant.themeIconColor}
                                />
                            </TouchableOpacity> : null
                        }
                    </View>
                    {result && result.length > 0 ?
                        // <FlatList
                        //     data={filterData}
                        //     renderItem={item => this._renderItem(item)}
                        //     keyExtractor={item => item.idNumber+''+item.name}
                        //     onMomentumScrollBegin={() => {
                        //         this.refs.input.blur();
                        //     }}
                        // />
                        <>
                            <TreeSelect
                                data={filterData}
                                // isOpen
                                // openIds={['A01']}
                                // defaultSelectedId={['B062']}
                                isShowTreeId={false}
                                selectType="single"
                                // selectType="multiple"
                                itemStyle={{
                                    // backgroudColor: '#8bb0ee',
                                    fontSize: 16,
                                    color: '#209bf6'
                                }}
                                selectedItemStyle={{
                                    backgroudColor: '#fff',
                                    fontSize: 18,
                                    color: '#e55757'
                                }}
                                onClick={(item)=>this._onClick(item)}
                                onClickLeaf={this._onClickLeaf}
                                treeNodeStyle={{
                                    openIcon: <FontAwesome
                                            name={'caret-down'}
                                            size={16}
                                            style={{color: StylesConstant.themeIconColor}} />,
                                    closeIcon: <FontAwesome
                                        name={'caret-right'}
                                        size={16}
                                        style={{color: StylesConstant.themeIconColor}} />
                                }}
                            />
                            <View style={{marginBottom: 5,alignItems: 'center'}}>
                                <Button
                                    style={[{width: '50%'}]}
                                    type="primary"
                                    size={'large'}
                                    onPress={() => this._chooseData()}
                                >
                                    选择
                                </Button>
                            </View>
                        </>
                        : <View style={{alignItems: 'center'}}>
                            <Text style={{color: '#999'}}>{loading?'加载中,请耐心等待...':'未找到相关数据'}</Text>
                        </View>
                    }
                </View>
            </Modal>
        );
    }

    render() {
        let view = <View style={GlobalStyles.root_container}>
            {this.renderContentView()}
        </View>;
        return view;
    }

}
